// pages/chat/chat.js
const app = getApp();
Page({
  data: {
    //userInfo:null
    interval: 5000,
    showView: true,
    scroll: false,
  },

  display_menu:function(e){
    this.setData({
      showView: (!this.data.showView),
      scroll: true
    })
  },

   /**
   * 滚动页面导航栏变色
   */
  onPageScroll:function (e) {
		if (e.scrollTop > 0) {
			this.setData({
				scroll: true
			});
		} else {
			this.setData({
				scroll: false
			});
		}
	},

  onLoad() {
    this.setData({
        userInfo : app.globalData.userInfo
    })
  },
  onShow() {
    this.setData({
      userInfo:app.globalData.userInfo
    })
    this.loadUser()
    setTimeout(() => {
      this.get_msgs()
    }, 800);
  },
  get_msgs(){
    var that=this;
    const dbc=wx.cloud.database().command;
    wx.cloud.database().collection('chat_record').where(
      dbc.or([
        {
          userA_id:app.globalData.userInfo._id,
          friend_status:true
        },
        {
          userB_id:app.globalData.userInfo._id,
          friend_status:true
        }
      ])
    ).watch({
      onChange: function(snapshot){
          that.setData({
            myMsglist : snapshot.docs
          })
      },
      onError : function(err){
          console.log(err)
      }
  })
  },
  loadUser() {
    var that = this;
    wx.cloud.database().collection('Users').where({
        nickName : that.data.userInfo.nickName,
    }).get({
        success(res) {
            console.log(res)
            // 更新数据 拿到 _id
            app.globalData.userInfo = res.data[0]
            that.setData({
                userInfo: app.globalData.userInfo
            })
        }
    })
  },
  startChat(e) {
    var index = e.currentTarget.dataset.index;
    console.log(this.data.myMsglist)
    wx.navigateTo({
      url: '/pages/chat_msg/chat_msg?id=' + this.data.myMsglist[index]._id
    })
  }
})
